package com.lyf.viewapp.nfc;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hf15693.NfcV.NfcVClassCard;
import com.example.hf15693.NfcV.NfcVUtil;
import com.lyf.viewapp.R;
import com.lyf.viewapp.base.BaseActivity;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 凯路威NFC标签读取-读多
 * @author lyf
 */
public class KlwReadMoreActivity extends BaseActivity {

    @BindView(R.id.tvrm15693)
    EditText tvrm15693;
    @BindView(R.id.tvrm)
    EditText tvrm;
    @BindView(R.id.btrm15693)
    Button btrm15693;
    @BindView(R.id.shuoming)
    TextView shuoming;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.Etime)
    EditText Etime;
    @BindView(R.id.uid)
    TextView uid;
    @BindView(R.id.euid)
    EditText euid;
    @BindView(R.id.tvrm1)
    TextView tvrm1;
    @BindView(R.id.eread)
    EditText eread;

    /**
     * 适配器
     */
    private static NfcAdapter mAdapter;
    /**
     * 延迟意图
     */
    private static PendingIntent mPendingIntent;
    /**
     * 过滤
     */
    private static IntentFilter[] mFilters;
    private static String[][] mTechLists;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_klw_read_more);
        ButterKnife.bind(this);
        tvrm15693.setText(Util.tvrm15693);
        tvrm.setText(Util.tvrm);
        mAdapter = NfcAdapter.getDefaultAdapter(this);
        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), 0);
        mTechLists = new String[][] { new String[] { NfcV.class.getName() } };
        Intent intent = getIntent();
        resolveIntent(intent);

    }

    private void resolveIntent(Intent intent) {
        if (!"android.nfc.action.TECH_DISCOVERED".equals(intent.getAction())) {
            return;
        }
        NfcV mNfcV = NfcV.get((Tag) intent
                .getParcelableExtra("android.nfc.extra.TAG"));
        NfcVClassCard nfcvcard = null;
        try {
            mNfcV.connect();
            NfcVUtil mNfcVutil = new NfcVUtil(mNfcV);
            String UID = mNfcVutil.Inventory().toUpperCase();
            uid.setText("UID:");
            euid.setVisibility(View.VISIBLE);
            euid.setText(UID);
            if (Util.tvrm15693 == null || Util.tvrm == null) {
                Toast.makeText(this, "请先确认配置数据", Toast.LENGTH_SHORT)
                        .show();
            } else {
                SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                String startTime = df.format(new Date());
                // 此处是读写块数，成燃项目固定为2块*8位即可
                int str = Integer.parseInt(Util.tvrm15693.toString());
                int str1 = Integer.parseInt(Util.tvrm.toString());
                byte[] str2 = mNfcVutil.readBlocks(str, str1);

                String info = NfcVUtil.bytesToHexString(str2).toUpperCase();
                String info1 = new String(str2);
                Toast.makeText(this, info1, Toast.LENGTH_SHORT).show();
                // String code=mNfcVutil.encode(info);
                tvrm1.setText("第" + str + "块到第" + (str1 + str - 1) + "块数据为：");
                eread.setVisibility(View.VISIBLE);
                eread.setText(info);
                String endTime = df.format(new Date());

                String diff = getUseTime(startTime, endTime);
                time.setText("用时:");
                Etime.setVisibility(View.VISIBLE);
                Etime.setText(diff + "毫秒");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (nfcvcard != null) {
                nfcvcard.debugPrint();
            }
        }
    }

    @Override
    public void onResume() {// 重新开始
        super.onResume();
        mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
                mTechLists);
    }

    @Override
    public void onNewIntent(Intent intent) {
        // 新意图
        resolveIntent(intent);
    }

    @OnClick({R.id.btrm15693})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btrm15693:
                Util.tvrm15693 = tvrm15693.getText().toString();
                // tvrm15693.setText(a);
                Util.tvrm = tvrm.getText().toString();
                // tvrm.setText(b);
                Toast.makeText(this, "设置成功", Toast.LENGTH_SHORT).show();
                shuoming.setText("提示：数据设置成功后，请将芯片靠近手机，待读取到数据后方可将芯片拿走");
                break;
                default:break;
        }
    }

    public void DisplayMsg(int resourceId, String title) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle(title);
        b.setMessage(resourceId);
        b.show();
    }

    private String getUseTime(String startTime, String endTime) {
        Calendar cStart = Calendar.getInstance();
        cStart.clear();
        cStart.set(Integer.parseInt(startTime.substring(0, 4)),
                Integer.parseInt(startTime.substring(4, 6)),
                Integer.parseInt(startTime.substring(6, 8)),
                Integer.parseInt(startTime.substring(8, 10)),
                Integer.parseInt(startTime.substring(10, 12)),
                Integer.parseInt(startTime.substring(12, 14)));
        Calendar cEnd = Calendar.getInstance();
        cEnd.clear();
        cEnd.set(Integer.parseInt(endTime.substring(0, 4)),
                Integer.parseInt(endTime.substring(4, 6)),
                Integer.parseInt(endTime.substring(6, 8)),
                Integer.parseInt(endTime.substring(8, 10)),
                Integer.parseInt(endTime.substring(10, 12)),
                Integer.parseInt(endTime.substring(12, 14)));
        long useTime = cEnd.getTimeInMillis() - cStart.getTimeInMillis();

        // 这里算出来的 是时间差 精确到毫秒 如果要精确到秒就自己再除1000
        return useTime + "";
    }
}
